package com.example.controller;


import com.example.service.CompetitionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.SetOperations;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * @Description //TODO
 * @Date 2022/9/21 8:51
 * @Author cxy
 **/
@ResponseBody
@Controller
@RestController
@RequestMapping("competition")
public class CompetitionController {
    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private CompetitionService competitionService;

    @PostMapping("enroll/{tid}")
    public Long dawncount(@PathVariable("tid")Integer tid){
        return competitionService.downCount(tid);
    }

    @GetMapping("enroll/{id}")
    public Map<String,Object> competition(HttpServletRequest request,@PathVariable("id")Integer id){
        String username = (String) request.getAttribute("username");
        System.out.println(username);
        Map<String,Object>resultMap =new HashMap<>();
        //redis里获取status

        String status =competitionService.getStatus(id);
        if("0".equals(status)){
            resultMap.put("code","-1");
            resultMap.put("msg","sorry,竞赛报名尚未开始!");
            return resultMap;
        }

        if("2".equals(status)){
            resultMap.put("code","2");
            resultMap.put("msg","sorry,竞赛报名已经结束了!");
            return resultMap;
        }
        Object o=redisTemplate.opsForList().leftPop("c_"+id);

        if(o==null){
            resultMap.put("code",404);
            resultMap.put("msg","sorry,报名名额已达上限！");
            return resultMap;
        }

        SetOperations set=redisTemplate.opsForSet();

        if (set.isMember("c_enroll_"+id,username)){
            resultMap.put("code","500");
            resultMap.put("msg","sorry,不能够重复报名!");
            redisTemplate.opsForList().leftPush("c_"+id,o);
            return resultMap;
        }

        set.add("c_enroll_"+id,username);
        resultMap.put("code","200");
        resultMap.put("msg","恭喜您报名成功!");
        //4. 将秒杀的信息=>投递到rbm-server

        competitionService.saveToRbm(id,username);

        return resultMap;
    }
}
